package com.reebake.ideal.holder;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.reebake.ideal.constants.CommonConstants;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 用户信息上下文
 */
public class UserContextHolder {
    private static final ThreadLocal<String> LOCAL_USER_ID = new InheritableThreadLocal<>();
    private static final ThreadLocal<Long> LOCAL_TENANT_ID = new InheritableThreadLocal<>();

    /**
     * 获取当前会话的用户编号
     * @return 用户编号
     */
    public static String getCurrentUserId() {
        // 提取用户编号
        String userId = LOCAL_USER_ID.get();
        if (StrUtil.isBlank(userId)) {
            HttpServletRequest request = getRequest();
            if (ObjUtil.isNotNull(request)) {
                userId = request.getHeader(CommonConstants.HEADER_NAME_USER_ID);
            }
        }

        return userId;
    }

    /**
     * 设置会话的用户编号
     * @param userId 用户编号
     */
    public static void setCurrentUserId(String userId) {
        LOCAL_USER_ID.set(userId);
    }

    /**
     * 获取当前会话的租户编号
     * @return 租户编号
     */
    public static Long getCurrentTenantId() {
        // 提取租户编号
        Long tenantId = LOCAL_TENANT_ID.get();
        if (ObjUtil.isNull(tenantId)) {
            HttpServletRequest request = getRequest();
            if (ObjUtil.isNotNull(request)) {
                String headerTenantId = request.getHeader(CommonConstants.HEADER_NAME_TENANT_ID);
                tenantId = StrUtil.isBlank(headerTenantId) ? null : Long.valueOf(headerTenantId);
            }
        }

        return tenantId;
    }

    /**
     * 设置租户编号
     * @param tenantId 租户编号
     */
    public static void setCurrentTenantId(Long tenantId) {
        LOCAL_TENANT_ID.set(tenantId);
    }

    /**
     * 获取请求
     * @return 请求
     */
    private static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return ObjUtil.isNull(requestAttributes) ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
    }
}
